package com.bizmerce.rnd.oms.cmmn.web;

import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;

import com.bizmerce.rnd.oms.util.ParamMap;

public class CustomWebArgumentResolver implements WebArgumentResolver {

    Log log = LogFactory.getLog(CustomWebArgumentResolver.class);

    @SuppressWarnings("unchecked")
    public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception {

        try {
            Class clazz = methodParameter.getParameterType();
            
            if ((clazz.equals(ParamMap.class))) {
                ParamMap map = new ParamMap();

                HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
                Enumeration <String> enumeration = request.getParameterNames();

                while (enumeration.hasMoreElements()) {
                    String key = (String) enumeration.nextElement();
                    String [] values = request.getParameterValues(key);
                    
                    map.put(key, (values.length > 1) ? values : values[0]);
                }
                
                // TODO 개발용
                map.put("cmpyCd", "bizmerce");
                map.put("userId", "admin");
                map.put("userDegree", "과장");
                
                if (log.isDebugEnabled()) {
                    log.debug("ParamMap Parameters:" + map);
                }
                
                return map;
            }
            
            if ((clazz.equals(HashMap.class))) {
                HashMap map = new HashMap();

                HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
                Enumeration <String> enumeration = request.getParameterNames();

                while (enumeration.hasMoreElements()) {
                    String key = (String) enumeration.nextElement();
                    String [] values = request.getParameterValues(key);
                    
                    if (values != null)
                        map.put(key, (values.length > 1) ? values : values[0]);
                    else
                        map.put(key, null);
                }
                
                if (log.isDebugEnabled()) {
                    log.debug("Request Parameters:" + map);
                }
                
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return UNRESOLVED;
    }

}
